﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace Kira.Compiler.Bods
{
    internal class DirectMapping : MappingBase
    {
        private DirectMapping(String name, Type eleType)
            : base(name, eleType)
        {
        }

        private static Dictionary<String, Type> _table;

        internal static DirectMapping Create(String name, Type eleType)
        {
            var instance = new DirectMapping(name, eleType);
            if (_table == null)
            {
                _table = new Dictionary<string, Type>();
            }
            if (_table.ContainsKey(instance.Key))
            {
                throw new Exception((new StringBuilder()).AppendFormat("Duplicated DirectMapping : {0} - {1}, already mapped to {2}", instance.Key, instance.ElementType, _table[instance.Key]).ToString());
            }
            else
            {
                _table.Add(instance.Key, instance.ElementType);
            }
            return instance;
        }

        internal static Type GetElementType(XElement xml)
        {
            if (_table == null)
            {
                throw new Exception("No DirectMapping registered.");
            }
            String key = xml.GetKey();
            if (_table.ContainsKey(key))
            {
                return _table[key];
            }
            else
            {
                throw new Exception((new StringBuilder()).AppendFormat("No DirectMapping found for {0}.", xml.Name).ToString());
            }
        }
    }
}
